package com.sto.stoapp.manager;

import com.sto.stoapp.log.ExceptionLog;
import com.sto.stoapp.widget.LockScreenLayout;

import android.content.Context;
import android.graphics.PixelFormat;
import android.view.Gravity;
import android.view.WindowManager;
import android.view.WindowManager.LayoutParams;



/**
 * 锁屏管理
 * 
 * @author hb
 * 
 */
public class LockScreenManager {

	/**
	 *  锁屏管理对象
	 */
	private static LockScreenManager lockScreenManager;

	/**
	 * 锁屏的实例
	 */
	private LockScreenLayout lockScreenLayout;

	/**
	 * 锁屏的参数
	 */
	private LayoutParams lockParams;

	/**
	 * 用于控制在屏幕上添加或移除悬浮窗
	 */
	private WindowManager mWindowManager;

	/**
	 * 实例化锁屏对象
	 * 
	 * @return
	 */
	public static LockScreenManager getInstance() {
		if (lockScreenManager == null) {
			lockScreenManager = new LockScreenManager();
		}

		return lockScreenManager;
	}

	/**
	 * 创建一个锁屏图片，位置为屏幕中间上方。
	 */
	public void createLockScreen(Context context) {
		try {
			if (lockScreenLayout == null) {
				mWindowManager = getWindowManager(context);
				int screenWidth = mWindowManager.getDefaultDisplay().getWidth();
				int screenHeight = mWindowManager.getDefaultDisplay()
						.getHeight();
				lockScreenLayout = new LockScreenLayout(context);
				if (lockParams == null) {
					lockParams = new LayoutParams();
					lockParams.flags = LayoutParams.FLAG_NOT_FOCUSABLE;
					lockParams.x = screenWidth / 2 - lockScreenLayout.width / 2;
					lockParams.y = screenHeight / 2 - 30;
					// lockParams.type = LayoutParams.TYPE_SYSTEM_ALERT;
					lockParams.format = PixelFormat.RGBA_8888;
					lockParams.gravity = Gravity.LEFT | Gravity.TOP;
					lockParams.width = lockScreenLayout.width;
					lockParams.height = lockScreenLayout.height;
				}
				mWindowManager.addView(lockScreenLayout, lockParams);
			}
		} catch (Exception e) {
			e.printStackTrace();
			ExceptionLog.writeLog("createLockScreen", e.getMessage());
		}
	}

	/**
	 * 关闭锁屏图片
	 */
	public void closeLockScreen() {
		try {
			if (mWindowManager != null) {
				mWindowManager.removeView(lockScreenLayout);
				mWindowManager = null;
			}
			if (lockScreenLayout != null) {
				lockScreenLayout.removeAllViews();
				lockScreenLayout = null;
			}
			if (lockParams != null) {
				lockParams = null;
			}
		} catch (Exception e) {
			e.printStackTrace();
			ExceptionLog.writeLog("closeLockScreen", e.getMessage());
		}

	}

	/**
	 * 如果WindowManager还未创建，则创建一个新的WindowManager返回。否则返回当前已创建的WindowManager。
	 * 
	 * @param context
	 *            必须为应用程序的Context.
	 * @return WindowManager的实例，用于控制在屏幕上添加或移除悬浮窗。
	 */
	private WindowManager getWindowManager(Context context) {
		WindowManager mWindowManager = null;

		try {
			mWindowManager = (WindowManager) context
					.getSystemService(Context.WINDOW_SERVICE);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return mWindowManager;
	}
}
